import { onMounted, onUnmounted, ref } from 'vue'

export default function useFullScreen() {
  // 当浏览器不支持全屏模式时，隐藏全屏按钮
  const enableFullscreen = document.fullscreenEnabled
  const fullscreen = ref(document.fullscreenElement === document.documentElement)

  function changeFullscreen() {
    if (!fullscreen.value) {
      // 进入全屏
      if (document.fullscreenElement != null) {
        return
      }
      document.documentElement.requestFullscreen()
      return
    }
    // 退出全屏
    if (document.fullscreenElement !== document.documentElement) {
      return
    }
    document.exitFullscreen()
  }

  // 禁用F11按下后的原生全屏，改由组件控制
  function onNativeFullscreenChange(e: KeyboardEvent) {
    if (e.key === 'F11') {
      e.preventDefault()
      changeFullscreen()
    }
  }

  // 通过监听事件来改变组件中的状态属性，而不是直接在调用API后更改，可避免通过按键退出时导致状态未变化
  function updateFullscreenStatus() {
    fullscreen.value = document.fullscreenElement != null
  }

  onMounted(() => {
    document.addEventListener('keydown', onNativeFullscreenChange)
    document.addEventListener('fullscreenchange', updateFullscreenStatus)
  })
  onUnmounted(() => {
    document.removeEventListener('keydown', onNativeFullscreenChange)
    document.removeEventListener('fullscreenchange', updateFullscreenStatus)
  })

  return {
    enableFullscreen,
    fullscreen,
    changeFullscreen
  }
}
